 
package com.spider.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

 
public class Function {
	private static Logger logger = Logger.getLogger(Function.class);
    public static String SPIDER_DATA_RECORD = "spider_data_record.properties"; 
	
    /**
     * 从配置文件中读取value
     * @param key
     * @return
     */
    public String getProValue(String key){
		Properties prop = new Properties();// 属性集合对象  
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(getRootPath());
			prop.load(fis);// 将属性文件流装载到Properties对象中  
		} catch (Exception e) {
			logger.info(e);
		}finally {
			if (fis != null) {
				try {
					fis.close();// 关闭流  
				} catch (IOException e) {
					logger.info(e);
				}
			}
		}
        
		return prop.getProperty(key); 
	}
    /**
     * 向配置文件设置key-value
     * @param map
     */
    public void setProValue(Map<String,String> map) {  
        if (null != map) {
			Properties prop = new Properties();// 属性集合对象  
			FileInputStream fis = null;
			FileOutputStream fos = null;
			try {
				fis = new FileInputStream(getRootPath());// 属性文件输入流  
				prop.load(fis);// 将属性文件流装载到Properties对象中  
				// 修改属性值  
				Set<Entry<String, String>> set = map.entrySet();
				if (null != set) {
					Iterator<Entry<String, String>> iterator = set.iterator();
					while(iterator.hasNext()){
						Entry<String, String> entry = iterator.next();
						prop.setProperty(entry.getKey(), entry.getValue());
					}
				}
				// 文件输出流  
				fos = new FileOutputStream(getRootPath());
				// 将Properties集合保存到流中  
				prop.store(fos, "Copyright (c) Boxcode Studio");
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (null != fos) {
						fos.close();// 关闭流  
					}
					if (null != fis) {
						fis.close();// 关闭流  
					}
				} catch (Exception e) {
					logger.info(e);
				}
			} 
		}  
    } 
    
    /**
	 * 手机号验证
	 * 
	 * @param  str
	 * @return 验证通过返回true
	 */
	public static boolean isMobile(String str) { 
		Pattern p = null;
		Matcher m = null;
		boolean b = false; 
		p = Pattern.compile("^[1][3,4,5,7,8][0-9]{9}$"); // 验证手机号
		m = p.matcher(str);
		b = m.matches(); 
		return b;
	}
	/**
	 * 获取服务器项目路径
	 * @return
	 */
	public String getRootPath(){
		String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();  
		String rootPath = path.substring(0, path.lastIndexOf("/classes"));  
		String propertyFilePath = rootPath  
		        + "/classes/"+SPIDER_DATA_RECORD; 
		return propertyFilePath;
	}
	/**
	 * 下载图片到本地
	 * @param picUrl 图片Url
	 * @param localPath 本地保存图片地址
	 * @return
	 */
	public String downloadPic(String picUrl,String localPath){
		String filePath = null;
		String url = null;
		try {  
            URL httpurl = new URL(picUrl);  
            String fileName = getFileNameFromUrl(picUrl);  
            filePath = localPath + fileName;
            File f = new File(filePath);  
            FileUtils.copyURLToFile(httpurl, f); 
            url = filePath.replace("/data/cydata", "http://wapimg1.cycares.com");
        } catch (Exception e) {  
            logger.info(e);  
            return null;  
        } 
        return url;
	}
	
	/**
	 * 下载图片到本地
	 * @param picUrl 图片Url
	 * @param localPath 本地保存图片地址
	 * @return
	 */
	public String downloadPicForNews(String picUrl,String localPath){
		String filePath = null;
		String url = null;
		try {  
			String newUrl = picUrl.replace("water/water_", "");
            URL httpurl = new URL(newUrl);  
            String fileName = getFileNameFromUrl(newUrl);  
            filePath = localPath + fileName;
            File f = new File(filePath);  
            FileUtils.copyURLToFile(httpurl, f); 
            url = filePath.replace("/data/cydata", "http://wapimg1.cycares.com");
        } catch (Exception e) {  
            logger.info(e);  
            return null;  
        } 
        return url;
	}
	
	
	/**
	 * 根据url获取文件名
	 * @param url 
	 * @return 文件名
	 */
	public static String getFileNameFromUrl(String url){  
        String name = new Long(System.currentTimeMillis()).toString() + ".X";  
        int index = url.lastIndexOf("/");  
        if(index > 0){  
            name = url.substring(index + 1);  
            if(name.trim().length()>0){  
                return name;  
            }  
        }  
        return name;  
    }
	public static void main(String[] args) {
		Function fun = new Function();
//		String path = fun.getProValue("baike_pic_file_path");
//		String url = "http://cdn.120askimages.com/ask/upload/baike/art/month_1608/201608050905035934.png";
//		String name = getFileNameFromUrl(url);
//		//System.out.println(name);
//		String pic = fun.downloadPic(url, path);
//		//System.out.println(pic);
//		
		
		String url = "http://cdn.120askimages.com/ask/upload/job/article/201608/water/water_201608252136385255.jpg";
//		String replace = url.replace("water/water_", "");
//		//System.out.println(replace);
		String nu = fun.downloadPicForNews(url, fun.getProValue("baike_pic_file_path"));
		System.err.println(nu);
		
	}
}

